package com.zzh.partnersys.ai.controller;

import com.zzh.partnersys.ai.entity.dto.DocumentParseTaskStatusDTO;
import com.zzh.partnersys.ai.service.DocumentParseService;
import com.zzh.partnersys.ai.service.DocumentParseTaskService;
import com.zzh.partnersys.common.exception.ResultCodeEnum;
import com.zzh.partnersys.common.exception.ResultUtils;
import com.zzh.partnersys.common.util.TokenUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

/**
 * 文档解析控制器
 *
 * @author zzh
 */
@Slf4j
@RestController
@RequestMapping("/document")
public class DocumentParseController {

    @Resource
    private DocumentParseService documentParseService;

    @Resource
    private DocumentParseTaskService documentParseTaskService;

    /**
     * 解析文档（异步）
     *
     * @param assistantId 助手ID
     * @param docList     文档列表
     * @param request     Http请求
     * @return 任务ID（UUID）
     */
    @PostMapping("/parse")
    public ResultUtils<ParseTaskResponse> parseDocuments(
            @RequestParam("assistantId") Long assistantId,
            @RequestBody List<DocumentParseRequest> docList,
            HttpServletRequest request) {
        
        // 获取当前用户ID
        Long userId = TokenUtils.getCurrentUserIdOrThrow(request);
        
        // 参数校验
        if (docList == null || docList.isEmpty()) {
            return ResultUtils.ok(null);
        }
        
        // 生成任务ID
        String taskId = UUID.randomUUID().toString();
        
        // 创建任务状态
        documentParseTaskService.createTask(taskId, docList.size());
        
        // 异步执行文档解析
        CompletableFuture.runAsync(() -> {
            try {
                int totalCount = docList.size();
                for (int i = 0; i < docList.size(); i++) {
                    final int currentIndex = i;
                    DocumentParseRequest docRequest = docList.get(i);
                    
                    // 更新进度：开始处理文档
                    int progress = (int) ((currentIndex * 100.0) / totalCount);
                    documentParseTaskService.updateProgress(
                            taskId,
                            currentIndex + 1,
                            docRequest.getDocName(),
                            progress,
                            "正在解析文档: " + docRequest.getDocName()
                    );
                    
                    try {
                        // 解析单个文档
                        documentParseService.parseAndStoreDocument(
                                assistantId,
                                userId,
                                docRequest.getDocUrl(),
                                docRequest.getDocName(),
                                docRequest.getDocType(),
                                parseProgress -> {
                                    // 计算总体进度
                                    int overallProgress = (int) ((currentIndex * 100.0 + parseProgress.getProgress()) / totalCount);
                                    documentParseTaskService.updateProgress(
                                            taskId,
                                            currentIndex + 1,
                                            docRequest.getDocName(),
                                            overallProgress,
                                            parseProgress.getStatus()
                                    );
                                }
                        );
                        
                        // 标记文档完成
                        documentParseTaskService.addCompletedDoc(taskId, docRequest.getDocName());
                        
                    } catch (Exception e) {
                        log.error("文档解析失败，docName: {}", docRequest.getDocName(), e);
                        documentParseTaskService.addFailedDoc(taskId, docRequest.getDocName(), e.getMessage());
                    }
                }
                
                // 标记任务完成
                documentParseTaskService.markTaskSuccess(taskId);
                
            } catch (Exception e) {
                log.error("文档解析任务失败，taskId: {}", taskId, e);
                documentParseTaskService.markTaskFailed(taskId, e.getMessage());
            }
        });
        
        return ResultUtils.ok(new ParseTaskResponse(taskId));
    }

    /**
     * 查询文档解析任务状态
     *
     * @param taskId 任务ID
     * @return 任务状态
     */
    @GetMapping("/parse/status/{taskId}")
    public ResultUtils<DocumentParseTaskStatusDTO> getTaskStatus(@PathVariable("taskId") String taskId) {
        DocumentParseTaskStatusDTO statusDTO = documentParseTaskService.getTaskStatus(taskId);
        if (statusDTO == null) {
            return ResultUtils.build(null, ResultCodeEnum.DOCUMENT_NOT_FOUND);
        }
        return ResultUtils.ok(statusDTO);
    }

    /**
     * 文档解析请求
     */
    @Data
    public static class DocumentParseRequest {
        private String docUrl;
        private String docName;
        private String docType;
    }

    /**
     * 解析任务响应
     */
    @Data
    public static class ParseTaskResponse {
        private String taskId;

        public ParseTaskResponse(String taskId) {
            this.taskId = taskId;
        }
    }
}

